home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_xemacs.idb / usr / freeware / lib / xemacs-20.4 / lisp / viper / viper-util.el.z / viper-util.el
Encoding:
Text File  |  1998-05-21  |  45.8 KB  |  1,344 lines

  1. ;;; viper-util.el --- Utilities used by viper.el
  2.  
  3. ;; Copyright (C) 1994, 1995, 1996, 1997 Free Software Foundation, Inc.
  4.  
  5. ;; This file is part of GNU Emacs.
  6.  
  7. ;; GNU Emacs is free software; you can redistribute it and/or modify
  8. ;; it under the terms of the GNU General Public License as published by
  9. ;; the Free Software Foundation; either version 2, or (at your option)
  10. ;; any later version.
  11.  
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15. ;; GNU General Public License for more details.
  16.  
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs; see the file COPYING.  If not, write to the
  19. ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  20. ;; Boston, MA 02111-1307, USA.
  21.  
  22.  
  23. ;; Code
  24.  
  25. ;; Compiler pacifier
  26. (defvar viper-overriding-map)
  27. (defvar pm-color-alist)
  28. (defvar zmacs-region-stays)
  29. (defvar viper-minibuffer-current-face)
  30. (defvar viper-minibuffer-insert-face)
  31. (defvar viper-minibuffer-vi-face)
  32. (defvar viper-minibuffer-emacs-face)
  33. (defvar viper-replace-overlay-face)
  34. (defvar viper-fast-keyseq-timeout)
  35. (defvar ex-unix-type-shell)
  36. (defvar ex-unix-type-shell-options)
  37. (defvar viper-ex-tmp-buf-name)
  38. (defvar viper-syntax-preference)
  39.  
  40. (require 'cl)
  41. (require 'ring)
  42.  
  43. (if noninteractive
  44.     (eval-when-compile
  45.       (let ((load-path (cons (expand-file-name ".") load-path)))
  46.     (or (featurep 'viper-init)
  47.         (load "viper-init.el" nil nil 'nosuffix))
  48.     )))
  49. ;; end pacifier
  50.  
  51. (require 'viper-init)
  52.  
  53.  
  54. ;; A fix for NeXT Step
  55. ;; Should go away, when NS people fix the design flaw, which leaves the
  56. ;; two x-* functions undefined.
  57. (if (and (not (fboundp 'x-display-color-p)) (fboundp 'ns-display-color-p))
  58.     (fset 'x-display-color-p (symbol-function 'ns-display-color-p)))
  59. (if (and (not (fboundp 'x-color-defined-p)) (fboundp 'ns-color-defined-p))
  60.       (fset 'x-color-defined-p (symbol-function 'ns-color-defined-p)))
  61.  
  62.  
  63. ;;; XEmacs support
  64.  
  65.  
  66. (if viper-xemacs-p
  67.     (progn
  68.       (fset 'viper-read-event (symbol-function 'next-command-event))
  69.       (fset 'viper-make-overlay (symbol-function 'make-extent))
  70.       (fset 'viper-overlay-start (symbol-function 'extent-start-position))
  71.       (fset 'viper-overlay-end (symbol-function 'extent-end-position))
  72.       (fset 'viper-overlay-put (symbol-function 'set-extent-property))
  73.       (fset 'viper-overlay-p (symbol-function 'extentp))
  74.       (fset 'viper-overlay-get (symbol-function 'extent-property))
  75.       (fset 'viper-move-overlay (symbol-function 'set-extent-endpoints))
  76.       (if (viper-window-display-p)
  77.       (fset 'viper-iconify (symbol-function 'iconify-frame)))
  78.       (cond ((viper-has-face-support-p)
  79.          (fset 'viper-get-face (symbol-function 'get-face))
  80.          (fset 'viper-color-defined-p
  81.            (symbol-function 'valid-color-name-p))
  82.          )))
  83.   (fset 'viper-read-event (symbol-function 'read-event))
  84.   (fset 'viper-make-overlay (symbol-function 'make-overlay))
  85.   (fset 'viper-overlay-start (symbol-function 'overlay-start))
  86.   (fset 'viper-overlay-end (symbol-function 'overlay-end))
  87.   (fset 'viper-overlay-put (symbol-function 'overlay-put))
  88.   (fset 'viper-overlay-p (symbol-function 'overlayp))
  89.   (fset 'viper-overlay-get (symbol-function 'overlay-get))
  90.   (fset 'viper-move-overlay (symbol-function 'move-overlay))
  91.   (if (viper-window-display-p)
  92.       (fset 'viper-iconify (symbol-function 'iconify-or-deiconify-frame)))
  93.   (cond ((viper-has-face-support-p)
  94.      (fset 'viper-get-face (symbol-function 'internal-get-face))
  95.      (fset 'viper-color-defined-p (symbol-function 'x-color-defined-p))
  96.      )))
  97.  
  98.  
  99. (fset 'viper-characterp
  100.       (symbol-function
  101.        (if viper-xemacs-p 'characterp 'integerp)))
  102.  
  103. (defsubst viper-color-display-p ()
  104.   (if viper-emacs-p
  105.       (x-display-color-p)
  106.     (eq (device-class (selected-device)) 'color)))
  107.    
  108. (defsubst viper-get-cursor-color ()
  109.   (if viper-emacs-p
  110.       (cdr (assoc 'cursor-color (frame-parameters)))
  111.     (color-instance-name (frame-property (selected-frame) 'cursor-color))))
  112.   
  113. ;;(defun viper-set-face-pixmap (face pixmap)
  114. ;;  "Set face pixmap on a monochrome display."
  115. ;;  (if (and (viper-window-display-p) (not (viper-color-display-p)))
  116. ;;      (condition-case nil
  117. ;;      (set-face-background-pixmap face pixmap)
  118. ;;    (error
  119. ;;     (message "Pixmap not found for %S: %s" (face-name face) pixmap)
  120. ;;     (sit-for 1)))))
  121.  
  122.   
  123. ;; OS/2
  124. (cond ((eq (viper-device-type) 'pm)
  125.        (fset 'viper-color-defined-p
  126.          (function (lambda (color) (assoc color pm-color-alist))))))
  127.     
  128. ;; needed to smooth out the difference between Emacs and XEmacs
  129. ;;(defsubst viper-italicize-face (face)
  130. ;;  (if viper-xemacs-p
  131. ;;      (make-face-italic face)
  132. ;;    (make-face-italic face nil 'noerror)))
  133.     
  134. ;; test if display is color and the colors are defined
  135. ;;(defsubst viper-can-use-colors (&rest colors)
  136. ;;  (if (viper-color-display-p)
  137. ;;      (not (memq nil (mapcar 'viper-color-defined-p colors)))
  138. ;;    ))
  139.  
  140. ;; cursor colors
  141. (defun viper-change-cursor-color (new-color)
  142.   (if (and (viper-window-display-p)  (viper-color-display-p)
  143.        (stringp new-color) (viper-color-defined-p new-color)
  144.        (not (string= new-color (viper-get-cursor-color))))
  145.       (modify-frame-parameters
  146.        (selected-frame) (list (cons 'cursor-color new-color)))))
  147.      
  148. (defun viper-save-cursor-color ()
  149.   (if (and (viper-window-display-p) (viper-color-display-p))
  150.       (let ((color (viper-get-cursor-color)))
  151.     (if (and (stringp color) (viper-color-defined-p color)
  152.          (not (string= color viper-replace-overlay-cursor-color)))
  153.         (viper-overlay-put viper-replace-overlay 'viper-cursor-color color)))))
  154.     
  155. ;; restore cursor color from replace overlay
  156. (defsubst viper-restore-cursor-color-after-replace ()
  157.   (viper-change-cursor-color
  158.    (viper-overlay-get viper-replace-overlay 'viper-cursor-color)))
  159. (defsubst viper-restore-cursor-color-after-insert ()
  160.   (viper-change-cursor-color viper-saved-cursor-color))
  161.      
  162.    
  163.  
  164. ;; Check the current version against the major and minor version numbers
  165. ;; using op: cur-vers op major.minor If emacs-major-version or
  166. ;; emacs-minor-version are not defined, we assume that the current version
  167. ;; is hopelessly outdated.  We assume that emacs-major-version and
  168. ;; emacs-minor-version are defined.  Otherwise, for Emacs/XEmacs 19, if the
  169. ;; current minor version is < 10 (xemacs) or < 23 (emacs) the return value
  170. ;; will be nil (when op is =, >, or >=) and t (when op is <, <=), which may be
  171. ;; incorrect. However, this gives correct result in our cases, since we are
  172. ;; testing for sufficiently high Emacs versions.
  173. (defun viper-check-version (op major minor &optional type-of-emacs)
  174.   (if (and (boundp 'emacs-major-version) (boundp 'emacs-minor-version))
  175.       (and (cond ((eq type-of-emacs 'xemacs) viper-xemacs-p)
  176.          ((eq type-of-emacs 'emacs) viper-emacs-p)
  177.          (t t))
  178.        (cond ((eq op '=) (and (= emacs-minor-version minor)
  179.                   (= emacs-major-version major)))
  180.          ((memq op '(> >= < <=))
  181.           (and (or (funcall op emacs-major-version major)
  182.                (= emacs-major-version major))
  183.                (if (= emacs-major-version major)
  184.                (funcall op emacs-minor-version minor)
  185.              t)))
  186.          (t
  187.           (error "%S: Invalid op in viper-check-version" op))))
  188.     (cond ((memq op '(= > >=)) nil)
  189.       ((memq op '(< <=)) t))))
  190.       
  191.  
  192. (defun viper-get-visible-buffer-window (wind)
  193.   (if viper-xemacs-p
  194.       (get-buffer-window wind t)
  195.     (get-buffer-window wind 'visible)))
  196.     
  197.     
  198. ;; Return line position.
  199. ;; If pos is 'start then returns position of line start.
  200. ;; If pos is 'end, returns line end. If pos is 'mid, returns line center.
  201. ;; Pos = 'indent returns beginning of indentation.
  202. ;; Otherwise, returns point. Current point is not moved in any case."
  203. (defun viper-line-pos (pos)
  204.   (let ((cur-pos (point))
  205.         (result))
  206.     (cond
  207.      ((equal pos 'start)
  208.       (beginning-of-line))
  209.      ((equal pos 'end)
  210.       (end-of-line))
  211.      ((equal pos 'mid)
  212.       (goto-char (+ (viper-line-pos 'start) (viper-line-pos 'end) 2)))
  213.      ((equal pos 'indent)
  214.       (back-to-indentation))
  215.      (t   nil))
  216.     (setq result (point))
  217.     (goto-char cur-pos)
  218.     result))
  219.  
  220. ;; Emacs counts each multibyte character as several positions in the buffer, so
  221. ;; we use Emacs' chars-in-region. XEmacs is counting each char as just one pos,
  222. ;; so we can simply subtract. 
  223. (defun viper-chars-in-region (beg end &optional preserve-sign)
  224.   (let ((count (abs (if (fboundp 'chars-in-region)
  225.             (chars-in-region beg end)
  226.               (- end beg)))))
  227.     (if (and (< end beg) preserve-sign)
  228.     (- count)
  229.       count)))
  230.  
  231. ;; Test if POS is between BEG and END
  232. (defsubst viper-pos-within-region (pos beg end)
  233.   (and (>= pos (min beg end)) (>= (max beg end) pos)))
  234.  
  235.  
  236. ;; Like move-marker but creates a virgin marker if arg isn't already a marker.
  237. ;; The first argument must eval to a variable name.
  238. ;; Arguments: (var-name position &optional buffer).
  239. ;; 
  240. ;; This is useful for moving markers that are supposed to be local.
  241. ;; For this, VAR-NAME should be made buffer-local with nil as a default.
  242. ;; Then, each time this var is used in `viper-move-marker-locally' in a new
  243. ;; buffer, a new marker will be created.
  244. (defun viper-move-marker-locally (var pos &optional buffer)
  245.   (if (markerp (eval var))
  246.       ()
  247.     (set var (make-marker)))
  248.   (move-marker (eval var) pos buffer))
  249.  
  250.  
  251. ;; Print CONDITIONS as a message.
  252. (defun viper-message-conditions (conditions)
  253.   (let ((case (car conditions)) (msg (cdr conditions)))
  254.     (if (null msg)
  255.     (message "%s" case)
  256.       (message "%s: %s" case (mapconcat 'prin1-to-string msg " ")))
  257.     (beep 1)))
  258.  
  259.  
  260.  
  261. ;;; List/alist utilities
  262.     
  263. ;; Convert LIST to an alist
  264. (defun viper-list-to-alist (lst)
  265.   (let ((alist))
  266.     (while lst
  267.       (setq alist (cons (list (car lst)) alist))
  268.       (setq lst (cdr lst)))
  269.     alist))    
  270.  
  271. ;; Convert ALIST to a list.
  272. (defun viper-alist-to-list (alst)
  273.   (let ((lst))
  274.     (while alst
  275.       (setq lst (cons (car (car alst)) lst))
  276.       (setq alst (cdr alst)))
  277.     lst))
  278.  
  279. ;; Filter ALIST using REGEXP. Return alist whose elements match the regexp.
  280. (defun viper-filter-alist (regexp alst)
  281.   (interactive "s x")
  282.   (let ((outalst) (inalst alst))
  283.     (while (car inalst)
  284.       (if (string-match regexp (car (car inalst)))
  285.       (setq outalst (cons (car inalst) outalst)))
  286.       (setq inalst (cdr inalst)))
  287.     outalst))    
  288.        
  289. ;; Filter LIST using REGEXP. Return list whose elements match the regexp.
  290. (defun viper-filter-list (regexp lst)
  291.   (interactive "s x")
  292.   (let ((outlst) (inlst lst))
  293.     (while (car inlst)
  294.       (if (string-match regexp (car inlst))
  295.       (setq outlst (cons (car inlst) outlst)))
  296.       (setq inlst (cdr inlst)))
  297.     outlst))    
  298.  
  299.    
  300. ;; Append LIS2 to LIS1, both alists, by side-effect and returns LIS1
  301. ;; LIS2 is modified by filtering it: deleting its members of the form
  302. ;; \(car elt\) such that (car elt') is in LIS1.
  303. (defun viper-append-filter-alist (lis1 lis2)
  304.   (let ((temp lis1)
  305.     elt)
  306.   
  307.     ;;filter-append the second list
  308.     (while temp
  309.       ;; delete all occurrences
  310.       (while (setq elt (assoc (car (car temp)) lis2))
  311.     (setq lis2 (delq elt lis2)))
  312.       (setq temp (cdr temp)))
  313.     
  314.     (nconc lis1 lis2)))
  315.  
  316.  
  317. ;;; Support for :e and file globbing
  318.  
  319. (defun viper-ex-nontrivial-find-file-unix (filespec)
  320.   "Glob the file spec and visit all files matching the spec.
  321. This function is designed to work under Unix. It may also work under VMS.
  322.  
  323. Users who prefer other types of shells should write their own version of this
  324. function and set the variable `ex-nontrivial-find-file-function'
  325. appropriately." 
  326.   (let ((gshell
  327.      (cond (ex-unix-type-shell shell-file-name)
  328.            ((memq system-type '(vax-vms axp-vms)) "*dcl*") ; VAX VMS
  329.            (t "sh"))) ; probably Unix anyway
  330.     (gshell-options
  331.      ;; using cond in anticipation of further additions
  332.      (cond (ex-unix-type-shell-options)
  333.            ))
  334.     (command (cond (viper-ms-style-os-p (format "\"ls -1 -d %s\"" filespec))
  335.                (t (format "ls -1 -d %s" filespec))))
  336.     file-list status)
  337.     (save-excursion 
  338.       (set-buffer (get-buffer-create viper-ex-tmp-buf-name))
  339.       (erase-buffer)
  340.       (setq status
  341.         (if gshell-options
  342.         (call-process gshell nil t nil
  343.                   gshell-options
  344.                   "-c"
  345.                   command)
  346.           (call-process gshell nil t nil
  347.                 "-c"
  348.                 command)))
  349.       (goto-char (point-min))
  350.       ;; Issue an error, if no match.
  351.       (if (> status 0)
  352.       (save-excursion
  353.         (skip-chars-forward " \t\n\j")
  354.         (if (looking-at "ls:")
  355.         (viper-forward-Word 1))
  356.         (error "%s: %s"
  357.            (if (stringp  gshell)
  358.                gshell
  359.              "shell")
  360.            (buffer-substring (point) (viper-line-pos 'end)))
  361.         ))
  362.       (goto-char (point-min))
  363.       (setq file-list (viper-get-filenames-from-buffer 'one-per-line)))
  364.  
  365.     (mapcar 'find-file file-list)
  366.     ))
  367.  
  368. (defun viper-ex-nontrivial-find-file-ms (filespec)
  369.   "Glob the file spec and visit all files matching the spec.
  370. This function is designed to work under MS type systems, such as NT, W95, and
  371. DOS. It may also work under OS/2.
  372.  
  373. The users of Unix-type shells should be able to use
  374. `viper-ex-nontrivial-find-file-unix', making it into the value of the variable 
  375. `ex-nontrivial-find-file-function'. If this doesn't work, the user may have
  376. to write a custom function, similar to `viper-ex-nontrivial-find-file-unix'."
  377.   (save-excursion 
  378.     (set-buffer (get-buffer-create viper-ex-tmp-buf-name))
  379.     (erase-buffer)
  380.     (insert filespec)
  381.     (goto-char (point-min))
  382.     (mapcar 'find-file
  383.         (viper-glob-ms-windows-files (viper-get-filenames-from-buffer)))
  384.     ))
  385.  
  386.  
  387. ;; Interpret the stuff in the buffer as a list of file names
  388. ;; return a list of file names listed in the buffer beginning at point
  389. ;; If optional arg is supplied, assume each filename is listed on a separate
  390. ;; line
  391. (defun viper-get-filenames-from-buffer (&optional one-per-line)
  392.   (let ((skip-chars (if one-per-line "\t\n" " \t\n"))
  393.      result fname delim)
  394.     (skip-chars-forward skip-chars)
  395.     (while (not (eobp))
  396.       (if (cond ((looking-at "\"")
  397.          (setq delim ?\")
  398.          (re-search-forward "[^\"]+" nil t)) ; noerror
  399.         ((looking-at "'")
  400.          (setq delim ?')
  401.          (re-search-forward "[^']+" nil t)) ; noerror
  402.         (t 
  403.          (re-search-forward
  404.           (concat "[^" skip-chars "]+") nil t))) ;noerror
  405.       (setq fname
  406.         (buffer-substring (match-beginning 0) (match-end 0))))
  407.       (if delim
  408.       (forward-char 1))
  409.       (skip-chars-forward " \t\n")
  410.       (setq result (cons fname result)))
  411.     result))
  412.  
  413. ;; convert MS-DOS wildcards to regexp
  414. (defun viper-wildcard-to-regexp (wcard)
  415.   (save-excursion
  416.     (set-buffer (get-buffer-create viper-ex-tmp-buf-name))
  417.     (erase-buffer)
  418.     (insert wcard)
  419.     (goto-char (point-min))
  420.     (while (not (eobp))
  421.       (skip-chars-forward "^*?.\\\\")
  422.       (cond ((eq (char-after (point)) ?*) (insert ".")(forward-char 1))
  423.         ((eq (char-after (point)) ?.) (insert "\\")(forward-char 1))
  424.         ((eq (char-after (point)) ?\\) (insert "\\")(forward-char 1))
  425.         ((eq (char-after (point)) ??) (delete-char 1)(insert ".")))
  426.       )
  427.     (buffer-string)
  428.     ))
  429.  
  430.  
  431. ;; glob windows files
  432. ;; LIST is expected to be in reverse order
  433. (defun viper-glob-ms-windows-files (list)
  434.   (let ((tmp list)
  435.     (case-fold-search t)
  436.     tmp2)
  437.     (while tmp
  438.       (setq tmp2 (cons (directory-files 
  439.             ;; the directory part
  440.             (or (file-name-directory (car tmp))
  441.                 "")
  442.             t  ; return full names
  443.             ;; the regexp part: globs the file names
  444.             (concat "^"
  445.                 (viper-wildcard-to-regexp
  446.                  (file-name-nondirectory (car tmp)))
  447.                 "$"))
  448.                tmp2))
  449.       (setq tmp (cdr tmp)))
  450.     (reverse (apply 'append tmp2))))
  451.  
  452.  
  453. ;;; Insertion ring
  454.  
  455. ;; Rotate RING's index. DIRection can be positive or negative.
  456. (defun viper-ring-rotate1 (ring dir)
  457.   (if (and (ring-p ring) (> (ring-length ring) 0))
  458.       (progn
  459.     (setcar ring (cond ((> dir 0)
  460.                 (ring-plus1 (car ring) (ring-length ring)))
  461.                ((< dir 0)
  462.                 (ring-minus1 (car ring) (ring-length ring)))
  463.                ;; don't rotate if dir = 0
  464.                (t (car ring))))
  465.     (viper-current-ring-item ring)
  466.     )))
  467.     
  468. (defun viper-special-ring-rotate1 (ring dir)
  469.   (if (memq viper-intermediate-command
  470.         '(repeating-display-destructive-command
  471.           repeating-insertion-from-ring))
  472.       (viper-ring-rotate1 ring dir)
  473.     ;; don't rotate otherwise
  474.     (viper-ring-rotate1 ring 0)))
  475.     
  476. ;; current ring item; if N is given, then so many items back from the
  477. ;; current
  478. (defun viper-current-ring-item (ring &optional n)
  479.   (setq n (or n 0))
  480.   (if (and (ring-p ring) (> (ring-length ring) 0))
  481.       (aref (cdr (cdr ring)) (mod (- (car ring) 1 n) (ring-length ring)))))
  482.     
  483. ;; push item onto ring. the second argument is a ring-variable, not value.
  484. (defun viper-push-onto-ring (item ring-var)
  485.   (or (ring-p (eval ring-var))
  486.       (set ring-var (make-ring (eval (intern (format "%S-size" ring-var))))))
  487.   (or (null item) ; don't push nil
  488.       (and (stringp item) (string= item "")) ; or empty strings
  489.       (equal item (viper-current-ring-item (eval ring-var))) ; or old stuff
  490.       ;; Since viper-set-destructive-command checks if we are inside
  491.       ;; viper-repeat, we don't check whether this-command-keys is a `.'.  The
  492.       ;; cmd viper-repeat makes a call to the current function only if `.' is
  493.       ;; executing a command from the command history. It doesn't call the
  494.       ;; push-onto-ring function if `.' is simply repeating the last
  495.       ;; destructive command.  We only check for ESC (which happens when we do
  496.       ;; insert with a prefix argument, or if this-command-keys doesn't give
  497.       ;; anything meaningful (in that case we don't know what to show to the
  498.       ;; user).
  499.       (and (eq ring-var 'viper-command-ring)
  500.        (string-match "\\([0-9]*\e\\|^[ \t]*$\\|escape\\)"
  501.              (viper-array-to-string (this-command-keys))))
  502.       (viper-ring-insert (eval ring-var) item))
  503.   )
  504.   
  505.  
  506. ;; removing elts from ring seems to break it
  507. (defun viper-cleanup-ring (ring)
  508.   (or (< (ring-length ring) 2)
  509.       (null (viper-current-ring-item ring))
  510.       ;; last and previous equal
  511.       (if (equal (viper-current-ring-item ring)
  512.          (viper-current-ring-item ring 1))
  513.       (viper-ring-pop ring))))
  514.       
  515. ;; ring-remove seems to be buggy, so we concocted this for our purposes.
  516. (defun viper-ring-pop (ring)
  517.   (let* ((ln (ring-length ring))
  518.      (vec (cdr (cdr ring)))
  519.      (veclen (length vec))
  520.      (hd (car ring))
  521.      (idx (max 0 (ring-minus1 hd ln)))
  522.      (top-elt (aref vec idx)))
  523.     
  524.     ;; shift elements
  525.     (while (< (1+ idx) veclen)
  526.       (aset vec idx (aref vec (1+ idx)))
  527.       (setq idx (1+ idx)))
  528.     (aset vec idx nil)
  529.     
  530.     (setq hd (max 0 (ring-minus1 hd ln)))
  531.     (if (= hd (1- ln)) (setq hd 0))
  532.     (setcar ring hd) ; move head
  533.     (setcar (cdr ring) (max 0 (1- ln))) ; adjust length
  534.     top-elt
  535.     ))
  536.     
  537. (defun viper-ring-insert (ring item)
  538.   (let* ((ln (ring-length ring))
  539.      (vec (cdr (cdr ring)))
  540.      (veclen (length vec))
  541.      (hd (car ring))
  542.      (vecpos-after-hd (if (= hd 0) ln hd))
  543.      (idx ln))
  544.      
  545.     (if (= ln veclen)
  546.     (progn
  547.       (aset vec hd item) ; hd is always 1+ the actual head index in vec
  548.       (setcar ring (ring-plus1 hd ln)))
  549.       (setcar (cdr ring) (1+ ln))
  550.       (setcar ring (ring-plus1 vecpos-after-hd (1+ ln)))
  551.       (while (and (>= idx vecpos-after-hd) (> ln 0))
  552.     (aset vec idx (aref vec (1- idx)))
  553.     (setq idx (1- idx)))
  554.       (aset vec vecpos-after-hd item))
  555.     item))
  556.     
  557.  
  558. ;;; String utilities
  559.  
  560. ;; If STRING is longer than MAX-LEN, truncate it and print ...... instead
  561. ;; PRE-STRING is a string to prepend to the abbrev string.
  562. ;; POST-STRING is a string to append to the abbrev string.
  563. ;; ABBREV_SIGN is a string to be inserted before POST-STRING
  564. ;; if the orig string was truncated. 
  565. (defun viper-abbreviate-string (string max-len
  566.                      pre-string post-string abbrev-sign)
  567.   (let (truncated-str)
  568.     (setq truncated-str
  569.       (if (stringp string) 
  570.           (substring string 0 (min max-len (length string)))))
  571.     (cond ((null truncated-str) "")
  572.       ((> (length string) max-len)
  573.        (format "%s%s%s%s"
  574.            pre-string truncated-str abbrev-sign post-string))
  575.       (t (format "%s%s%s" pre-string truncated-str post-string)))))
  576.  
  577. ;; tells if we are over a whitespace-only line
  578. (defsubst viper-over-whitespace-line ()
  579.   (save-excursion
  580.     (beginning-of-line)
  581.     (looking-at "^[ \t]*$")))
  582.       
  583.  
  584. ;;; Saving settings in custom file
  585.  
  586. ;; Save the current setting of VAR in CUSTOM-FILE.
  587. ;; If given, MESSAGE is a message to be displayed after that.
  588. ;; This message is erased after 2 secs, if erase-msg is non-nil.
  589. ;; Arguments: var message custom-file &optional erase-message
  590. (defun viper-save-setting (var message custom-file &optional erase-msg)
  591.   (let* ((var-name (symbol-name var))
  592.      (var-val (if (boundp var) (eval var)))
  593.      (regexp (format "^[^;]*%s[ \t\n]*[a-zA-Z---_']*[ \t\n)]" var-name))
  594.      (buf (find-file-noselect (substitute-in-file-name custom-file)))
  595.     )
  596.     (message message)
  597.     (save-excursion
  598.       (set-buffer buf)
  599.       (goto-char (point-min))
  600.       (if (re-search-forward regexp nil t)
  601.       (let ((reg-end (1- (match-end 0))))
  602.         (search-backward var-name)
  603.         (delete-region (match-beginning 0) reg-end)
  604.         (goto-char (match-beginning 0))
  605.         (insert (format "%s  '%S" var-name var-val)))
  606.     (goto-char (point-max))
  607.     (if (not (bolp)) (insert "\n"))
  608.     (insert (format "(setq %s '%S)\n" var-name var-val)))
  609.       (save-buffer))
  610.       (kill-buffer buf)
  611.       (if erase-msg
  612.       (progn
  613.         (sit-for 2)
  614.         (message "")))
  615.       ))
  616.       
  617. ;; Save STRING in CUSTOM-FILE. If PATTERN is non-nil, remove strings that
  618. ;; match this pattern.
  619. (defun viper-save-string-in-file (string custom-file &optional pattern)
  620.   (let ((buf (find-file-noselect (substitute-in-file-name custom-file))))
  621.     (save-excursion
  622.       (set-buffer buf)
  623.       (goto-char (point-min))
  624.       (if pattern (delete-matching-lines pattern))
  625.       (goto-char (point-max))
  626.       (if string (insert string))
  627.       (save-buffer))
  628.     (kill-buffer buf)
  629.     ))
  630.     
  631.  
  632. ;;; Overlays
  633.  
  634. ;; Search
  635.  
  636. (defun viper-flash-search-pattern ()
  637.   (if (viper-overlay-p viper-search-overlay)
  638.       (viper-move-overlay
  639.        viper-search-overlay (match-beginning 0) (match-end 0))
  640.     (setq viper-search-overlay
  641.       (viper-make-overlay
  642.        (match-beginning 0) (match-end 0) (current-buffer))))
  643.   
  644.   (viper-overlay-put
  645.    viper-search-overlay 'priority viper-search-overlay-priority)
  646.   (if (viper-has-face-support-p)
  647.       (progn
  648.     (viper-overlay-put viper-search-overlay 'face viper-search-face)
  649.     (sit-for 2)
  650.     (viper-overlay-put viper-search-overlay 'face nil))))
  651.  
  652.  
  653. ;; Replace state
  654.  
  655. (defsubst viper-move-replace-overlay (beg end)
  656.   (viper-move-overlay viper-replace-overlay beg end))
  657.   
  658. (defun viper-set-replace-overlay (beg end)
  659.   (if (viper-overlay-p viper-replace-overlay)
  660.       (viper-move-replace-overlay beg end)
  661.     (setq viper-replace-overlay (viper-make-overlay beg end (current-buffer)))
  662.     ;; never detach
  663.     (viper-overlay-put
  664.      viper-replace-overlay (if viper-emacs-p 'evaporate 'detachable) nil)
  665.     (viper-overlay-put 
  666.      viper-replace-overlay 'priority viper-replace-overlay-priority)
  667.     ;; If Emacs will start supporting overlay maps, as it currently supports
  668.     ;; text-property maps, we could do away with viper-replace-minor-mode and
  669.     ;; just have keymap attached to replace overlay.
  670.     ;;(viper-overlay-put
  671.     ;; viper-replace-overlay
  672.     ;; (if viper-xemacs-p 'keymap 'local-map)
  673.     ;; viper-replace-map)
  674.     ) 
  675.   (if (viper-has-face-support-p)
  676.       (viper-overlay-put
  677.        viper-replace-overlay 'face viper-replace-overlay-face))
  678.   (viper-save-cursor-color)
  679.   (viper-change-cursor-color viper-replace-overlay-cursor-color)
  680.   )
  681.   
  682.       
  683. (defun viper-set-replace-overlay-glyphs (before-glyph after-glyph)
  684.   (if (or (not (viper-has-face-support-p))
  685.       viper-use-replace-region-delimiters)
  686.       (let ((before-name (if viper-xemacs-p 'begin-glyph 'before-string))
  687.         (after-name (if viper-xemacs-p 'end-glyph 'after-string)))
  688.     (viper-overlay-put viper-replace-overlay before-name before-glyph)
  689.     (viper-overlay-put viper-replace-overlay after-name after-glyph))))
  690.   
  691. (defun viper-hide-replace-overlay ()
  692.   (viper-set-replace-overlay-glyphs nil nil)
  693.   (viper-restore-cursor-color-after-replace)
  694.   (viper-restore-cursor-color-after-insert)
  695.   (if (viper-has-face-support-p)
  696.       (viper-overlay-put viper-replace-overlay 'face nil)))
  697.  
  698.     
  699. (defsubst viper-replace-start ()
  700.   (viper-overlay-start viper-replace-overlay))
  701. (defsubst viper-replace-end ()
  702.   (viper-overlay-end viper-replace-overlay))
  703.  
  704.  
  705. ;; Minibuffer
  706.  
  707. (defun viper-set-minibuffer-overlay ()
  708.   (viper-check-minibuffer-overlay)
  709.   (if (viper-has-face-support-p)
  710.       (progn
  711.     (viper-overlay-put
  712.      viper-minibuffer-overlay 'face viper-minibuffer-current-face)
  713.     (viper-overlay-put 
  714.      viper-minibuffer-overlay 'priority viper-minibuffer-overlay-priority)
  715.     ;; never detach
  716.     (viper-overlay-put
  717.      viper-minibuffer-overlay
  718.      (if viper-emacs-p 'evaporate 'detachable)
  719.      nil)
  720.     ;; make viper-minibuffer-overlay open-ended
  721.     ;; In emacs, it is made open ended at creation time
  722.     (if viper-xemacs-p
  723.         (progn
  724.           (viper-overlay-put viper-minibuffer-overlay 'start-open nil)
  725.           (viper-overlay-put viper-minibuffer-overlay 'end-open nil)))
  726.     )))
  727.        
  728. (defun viper-check-minibuffer-overlay ()
  729.   (or (viper-overlay-p viper-minibuffer-overlay)
  730.       (setq viper-minibuffer-overlay
  731.         (if viper-xemacs-p
  732.         (viper-make-overlay 1 (1+ (buffer-size)) (current-buffer))
  733.           ;; make overlay open-ended
  734.           (viper-make-overlay
  735.            1 (1+ (buffer-size)) (current-buffer) nil 'rear-advance)))
  736.       ))
  737.  
  738.  
  739. (defsubst viper-is-in-minibuffer ()
  740.   (string-match "\*Minibuf-" (buffer-name)))
  741.   
  742.  
  743.  
  744. ;;; XEmacs compatibility
  745.  
  746. (defun viper-abbreviate-file-name (file)
  747.   (if viper-emacs-p
  748.       (abbreviate-file-name file)
  749.     ;; XEmacs requires addl argument
  750.     (abbreviate-file-name file t)))
  751.     
  752. ;; Sit for VAL milliseconds. XEmacs doesn't support the millisecond arg 
  753. ;; in sit-for, so this function smoothes out the differences.
  754. (defsubst viper-sit-for-short (val &optional nodisp)
  755.   (if viper-xemacs-p
  756.       (sit-for (/ val 1000.0) nodisp)
  757.     (sit-for 0 val nodisp)))
  758.  
  759. ;; EVENT may be a single event of a sequence of events
  760. (defsubst viper-ESC-event-p (event)
  761.   (let ((ESC-keys '(?\e (control \[) escape))
  762.     (key (viper-event-key event)))
  763.     (member key ESC-keys)))
  764.  
  765. ;; checks if object is a marker, has a buffer, and points to within that buffer
  766. (defun viper-valid-marker (marker)
  767.   (if (and (markerp marker) (marker-buffer marker))
  768.       (let ((buf (marker-buffer marker))
  769.         (pos (marker-position marker)))
  770.     (save-excursion
  771.       (set-buffer buf)
  772.       (and (<= pos (point-max)) (<= (point-min) pos))))))
  773.   
  774. (defsubst viper-mark-marker ()
  775.   (if viper-xemacs-p
  776.       (mark-marker t)
  777.     (mark-marker)))
  778.  
  779. ;; like (set-mark-command nil) but doesn't push twice, if (car mark-ring)
  780. ;; is the same as (mark t).
  781. (defsubst viper-set-mark-if-necessary ()
  782.   (setq mark-ring (delete (viper-mark-marker) mark-ring))
  783.   (set-mark-command nil))
  784.        
  785. ;; In transient mark mode (zmacs mode), it is annoying when regions become
  786. ;; highlighted due to Viper's pushing marks. So, we deactivate marks, unless
  787. ;; the user explicitly wants highlighting, e.g., by hitting '' or ``
  788. (defun viper-deactivate-mark ()
  789.   (if viper-xemacs-p
  790.       (zmacs-deactivate-region)
  791.     (deactivate-mark)))
  792.  
  793. (defsubst viper-leave-region-active ()
  794.   (if viper-xemacs-p
  795.       (setq zmacs-region-stays t)))
  796.  
  797. ;; Check if arg is a valid character for register
  798. ;; TYPE is a list that can contain `letter', `Letter', and `digit'.
  799. ;; Letter means lowercase letters, Letter means uppercase letters, and
  800. ;; digit means digits from 1 to 9.
  801. ;; If TYPE is nil, then down/uppercase letters and digits are allowed.
  802. (defun viper-valid-register (reg &optional type)
  803.   (or type (setq type '(letter Letter digit)))
  804.   (or (if (memq 'letter type)
  805.       (and (<= ?a reg) (<= reg ?z)))
  806.       (if (memq 'digit type)
  807.       (and (<= ?1 reg) (<= reg ?9)))
  808.       (if (memq 'Letter type)
  809.       (and (<= ?A reg) (<= reg ?Z)))
  810.       ))
  811.  
  812.     
  813. (defsubst viper-events-to-keys (events)
  814.   (cond (viper-xemacs-p (events-to-keys events))
  815.     (t events)))
  816.           
  817.     
  818. ;; This is here because Emacs changed the way local hooks work.
  819. ;;
  820. ;;Add to the value of HOOK the function FUNCTION.
  821. ;;FUNCTION is not added if already present.
  822. ;;FUNCTION is added (if necessary) at the beginning of the hook list
  823. ;;unless the optional argument APPEND is non-nil, in which case
  824. ;;FUNCTION is added at the end.
  825. ;;
  826. ;;HOOK should be a symbol, and FUNCTION may be any valid function.  If
  827. ;;HOOK is void, it is first set to nil.  If HOOK's value is a single
  828. ;;function, it is changed to a list of functions."
  829. (defun viper-add-hook (hook function &optional append)
  830.   (if (not (boundp hook)) (set hook nil))
  831.   ;; If the hook value is a single function, turn it into a list.
  832.   (let ((old (symbol-value hook)))
  833.     (if (or (not (listp old)) (eq (car old) 'lambda))
  834.     (setq old (list old)))
  835.     (if (member function old)
  836.     nil
  837.       (set hook (if append
  838.             (append old (list function)) ; don't nconc
  839.           (cons function old))))))
  840.  
  841. ;; This is here because of Emacs's changes in the semantics of add/remove-hooks
  842. ;; and due to the bugs they introduced.
  843. ;;
  844. ;; Remove from the value of HOOK the function FUNCTION.
  845. ;; HOOK should be a symbol, and FUNCTION may be any valid function.  If
  846. ;; FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the
  847. ;; list of hooks to run in HOOK, then nothing is done.  See `viper-add-hook'."
  848. (defun viper-remove-hook (hook function)
  849.   (if (or (not (boundp hook))        ;unbound symbol, or
  850.       (null (symbol-value hook))    ;value is nil, or
  851.       (null function))        ;function is nil, then
  852.       nil                ;Do nothing.
  853.     (let ((hook-value (symbol-value hook)))
  854.       (if (consp hook-value)
  855.       ;; don't side-effect the list
  856.       (setq hook-value (delete function (copy-sequence hook-value)))
  857.     (if (equal hook-value function)
  858.         (setq hook-value nil)))
  859.       (set hook hook-value))))
  860.  
  861.     
  862. ;; it is suggested that an event must be copied before it is assigned to
  863. ;; last-command-event in XEmacs
  864. (defun viper-copy-event (event)
  865.   (if viper-xemacs-p
  866.       (copy-event event)
  867.     event))
  868.     
  869. ;; like read-event, but in XEmacs also try to convert to char, if possible
  870. (defun viper-read-event-convert-to-char ()
  871.   (let (event)
  872.     (if viper-emacs-p
  873.     (read-event)
  874.       (setq event (next-command-event))
  875.       (or (event-to-character event)
  876.       event))
  877.     ))
  878.  
  879. ;; This function lets function-key-map convert key sequences into logical
  880. ;; keys. This does a better job than viper-read-event when it comes to kbd
  881. ;; macros, since it enables certain macros to be shared between X and TTY modes
  882. ;; by correctly mapping key sequences for Left/Right/... (one an ascii
  883. ;; terminal) into logical keys left, right, etc.
  884. (defun viper-read-key () 
  885.   (let ((overriding-local-map viper-overriding-map) 
  886.     (inhibit-quit t)
  887.     help-char key) 
  888.     (use-global-map viper-overriding-map) 
  889.     (unwind-protect
  890.     (setq key (elt (read-key-sequence nil) 0)) 
  891.       (use-global-map global-map))
  892.     key))
  893.  
  894.  
  895. ;; Emacs has a bug in eventp, which causes (eventp nil) to return (nil)
  896. ;; instead of nil, if '(nil) was previously inadvertently assigned to
  897. ;; unread-command-events
  898. (defun viper-event-key (event)
  899.   (or (and event (eventp event))
  900.       (error "viper-event-key: Wrong type argument, eventp, %S" event))
  901.   (when (cond (viper-xemacs-p (or (key-press-event-p event)
  902.                   (mouse-event-p event)))
  903.           (t t))
  904.     (let ((mod (event-modifiers event))
  905.       basis)
  906.       (setq basis
  907.         (cond
  908.          (viper-xemacs-p
  909.           (cond ((key-press-event-p event)
  910.              (event-key event))
  911.             ((button-event-p event)
  912.              (concat "mouse-" (prin1-to-string (event-button event))))
  913.             (t 
  914.              (error "viper-event-key: Unknown event, %S" event))))
  915.          (t 
  916.           ;; Emacs doesn't handle capital letters correctly, since
  917.           ;; \S-a isn't considered the same as A (it behaves as
  918.           ;; plain `a' instead). So we take care of this here
  919.           (cond ((and (viper-characterp event) (<= ?A event) (<= event ?Z))
  920.              (setq mod nil
  921.                event event))
  922.             ;; Emacs has the oddity whereby characters 128+char
  923.             ;; represent M-char *if* this appears inside a string.
  924.             ;; So, we convert them manually to (meta char).
  925.             ((and (viper-characterp event)
  926.               (< ?\C-? event) (<= event 255))
  927.              (setq mod '(meta)
  928.                event (- event ?\C-? 1)))
  929.             ((and (null mod) (eq event 'return))
  930.              (setq event ?\C-m))
  931.             ((and (null mod) (eq event 'space))
  932.              (setq event ?\ ))
  933.             ((and (null mod) (eq event 'delete))
  934.              (setq event ?\C-?))
  935.             ((and (null mod) (eq event 'backspace))
  936.              (setq event ?\C-h))
  937.             (t (event-basic-type event)))
  938.           )))
  939.       (if (viper-characterp basis)
  940.       (setq basis
  941.         (if (= basis ?\C-?)
  942.             (list 'control '\?) ; taking care of an emacs bug
  943.           (intern (char-to-string basis)))))
  944.       (if mod
  945.       (append mod (list basis))
  946.     basis))))
  947.     
  948. (defun viper-key-to-emacs-key (key)
  949.   (let (key-name char-p modifiers mod-char-list base-key base-key-name)
  950.     (cond (viper-xemacs-p key)
  951.  
  952.       ((symbolp key)
  953.        (setq key-name (symbol-name key))
  954.        (cond ((= (length key-name) 1) ; character event
  955.           (string-to-char key-name))
  956.          ;; Emacs doesn't recognize `return' and `escape' as events on
  957.          ;; dumb terminals, so we translate them into characters
  958.          ((and viper-emacs-p (not (viper-window-display-p))
  959.                (string= key-name "return"))
  960.           ?\C-m)
  961.          ((and viper-emacs-p (not (viper-window-display-p))
  962.                (string= key-name "escape"))
  963.           ?\e)
  964.          ;; pass symbol-event as is
  965.          (t key)))
  966.  
  967.       ((listp key)
  968.        (setq modifiers (subseq key 0 (1- (length key)))
  969.          base-key (viper-seq-last-elt key)
  970.          base-key-name (symbol-name base-key)
  971.          char-p (= (length base-key-name) 1))
  972.        (setq mod-char-list
  973.          (mapcar
  974.           '(lambda (elt) (upcase (substring (symbol-name elt) 0 1)))
  975.           modifiers))
  976.        (if char-p
  977.            (setq key-name
  978.              (car (read-from-string
  979.                (concat
  980.                 "?\\"
  981.                 (mapconcat 'identity mod-char-list "-\\")
  982.                 "-"
  983.                 base-key-name))))
  984.          (setq key-name
  985.            (intern
  986.             (concat
  987.              (mapconcat 'identity mod-char-list "-")
  988.              "-"
  989.              base-key-name))))))
  990.     ))
  991.  
  992.  
  993. ;; Args can be a sequence of events, a string, or a Viper macro.  Will try to
  994. ;; convert events to keys and, if all keys are regular printable
  995. ;; characters, will return a string. Otherwise, will return a string
  996. ;; representing a vector of converted events. If the input was a Viper macro,
  997. ;; will return a string that represents this macro as a vector.
  998. (defun viper-array-to-string (event-seq)
  999.   (let (temp temp2)
  1000.     (cond ((stringp event-seq) event-seq)
  1001.       ((viper-event-vector-p event-seq)
  1002.         (setq temp (mapcar 'viper-event-key event-seq))
  1003.         (cond ((viper-char-symbol-sequence-p temp)
  1004.            (mapconcat 'symbol-name temp ""))
  1005.           ((and (viper-char-array-p
  1006.              (setq temp2 (mapcar 'viper-key-to-character temp))))
  1007.            (mapconcat 'char-to-string temp2 ""))
  1008.           (t (prin1-to-string (vconcat temp)))))
  1009.       ((viper-char-symbol-sequence-p event-seq)
  1010.        (mapconcat 'symbol-name event-seq ""))
  1011.       ((and (vectorp event-seq) 
  1012.         (viper-char-array-p
  1013.          (setq temp (mapcar 'viper-key-to-character event-seq))))
  1014.        (mapconcat 'char-to-string temp ""))
  1015.       (t (prin1-to-string event-seq)))))
  1016.  
  1017. (defun viper-key-press-events-to-chars (events)
  1018.   (mapconcat (if viper-emacs-p
  1019.          'char-to-string
  1020.            (function
  1021.         (lambda (elt) (char-to-string (event-to-character elt)))))
  1022.          events
  1023.          ""))
  1024.        
  1025.     
  1026. ;; Uses different timeouts for ESC-sequences and others
  1027. (defsubst viper-fast-keysequence-p ()
  1028.   (not (viper-sit-for-short 
  1029.     (if (viper-ESC-event-p last-input-event)
  1030.         viper-ESC-keyseq-timeout
  1031.       viper-fast-keyseq-timeout)
  1032.     t)))
  1033.     
  1034. (defun viper-read-char-exclusive ()
  1035.   (let (char
  1036.     (echo-keystrokes 1))
  1037.     (while (null char)
  1038.       (condition-case nil
  1039.       (setq char (read-char))
  1040.     (error
  1041.      ;; skip event if not char
  1042.      (viper-read-event))))
  1043.     char))
  1044.  
  1045. ;; key is supposed to be in viper's representation, e.g., (control l), a
  1046. ;; character, etc.
  1047. (defun viper-key-to-character (key)
  1048.   (cond ((eq key 'space) ?\ )
  1049.     ((eq key 'delete) ?\C-?)
  1050.     ((eq key 'return) ?\C-m)
  1051.     ((eq key 'backspace) ?\C-h)
  1052.     ((and (symbolp key)
  1053.           (= 1 (length (symbol-name key))))
  1054.      (string-to-char (symbol-name key)))
  1055.     ((and (listp key)
  1056.           (eq (car key) 'control)
  1057.           (symbol-name (nth 1 key))
  1058.           (= 1 (length (symbol-name (nth 1 key)))))
  1059.      (read (format "?\\C-%s" (symbol-name (nth 1 key)))))
  1060.     (t key)))
  1061.     
  1062.       
  1063. (defun viper-setup-master-buffer (&rest other-files-or-buffers)
  1064.   "Set up the current buffer as a master buffer.
  1065. Arguments become related buffers. This function should normally be used in
  1066. the `Local variables' section of a file."
  1067.   (setq viper-related-files-and-buffers-ring 
  1068.     (make-ring (1+ (length other-files-or-buffers))))
  1069.   (mapcar '(lambda (elt)
  1070.          (viper-ring-insert viper-related-files-and-buffers-ring elt))
  1071.       other-files-or-buffers)
  1072.   (viper-ring-insert viper-related-files-and-buffers-ring (buffer-name))
  1073.   )
  1074.  
  1075. ;;; Movement utilities
  1076.  
  1077. ;; Characters that should not be considered as part of the word, in reformed-vi
  1078. ;; syntax mode.
  1079. (defconst viper-non-word-characters-reformed-vi
  1080.   "!@#$%^&*()-+=|\\~`{}[];:'\",<.>/?")
  1081. ;; These are characters that are not to be considered as parts of a word in
  1082. ;; Viper.
  1083. ;; Set each time state changes and at loading time
  1084. (viper-deflocalvar viper-non-word-characters  nil)
  1085.  
  1086. ;; must be buffer-local
  1087. (viper-deflocalvar viper-ALPHA-char-class "w"
  1088.   "String of syntax classes characterizing Viper's alphanumeric symbols.
  1089. In addition, the symbol `_' may be considered alphanumeric if
  1090. `viper-syntax-preference' is `strict-vi' or `reformed-vi'.")
  1091.  
  1092. (defconst viper-strict-ALPHA-chars "a-zA-Z0-9_"
  1093.   "Regexp matching the set of alphanumeric characters acceptable to strict
  1094. Vi.")
  1095. (defconst viper-strict-SEP-chars " \t\n"
  1096.   "Regexp matching the set of alphanumeric characters acceptable to strict
  1097. Vi.")
  1098. (defconst viper-strict-SEP-chars-sans-newline " \t"
  1099.   "Regexp matching the set of alphanumeric characters acceptable to strict
  1100. Vi.")
  1101.  
  1102. (defconst viper-SEP-char-class " -"
  1103.   "String of syntax classes for Vi separators.
  1104. Usually contains ` ', linefeed, TAB or formfeed.")
  1105.  
  1106.  
  1107. ;; Set Viper syntax classes and related variables according to
  1108. ;; `viper-syntax-preference'.  
  1109. (defun viper-update-syntax-classes (&optional set-default)
  1110.   (let ((preference (cond ((eq viper-syntax-preference 'emacs)
  1111.                "w")   ; Viper words have only Emacs word chars
  1112.               ((eq viper-syntax-preference 'extended)
  1113.                "w_")  ; Viper words have Emacs word & symbol chars
  1114.               (t "w"))) ; Viper words are Emacs words plus `_'
  1115.     (non-word-chars (cond ((eq viper-syntax-preference 'reformed-vi)
  1116.                    (viper-string-to-list
  1117.                 viper-non-word-characters-reformed-vi))
  1118.                   (t nil))))
  1119.     (if set-default
  1120.     (setq-default viper-ALPHA-char-class preference
  1121.               viper-non-word-characters non-word-chars)
  1122.       (setq viper-ALPHA-char-class preference
  1123.         viper-non-word-characters non-word-chars))
  1124.     ))
  1125.  
  1126. ;; SYMBOL is used because customize requires it, but it is ignored, unless it
  1127. ;; is `nil'. If nil, use setq.
  1128. (defun viper-set-syntax-preference (&optional symbol value)
  1129.   "Set Viper syntax preference.
  1130. If called interactively or if SYMBOL is nil, sets syntax preference in current
  1131. buffer. If called non-interactively, preferably via the customization widget,
  1132. sets the default value."
  1133.   (interactive)
  1134.   (or value
  1135.       (setq value
  1136.         (completing-read
  1137.          "Viper syntax preference: "
  1138.          '(("strict-vi") ("reformed-vi") ("extended") ("emacs"))
  1139.          nil 'require-match)))
  1140.   (if (stringp value) (setq value (intern value)))
  1141.   (or (memq value '(strict-vi reformed-vi extended emacs))
  1142.       (error "Invalid Viper syntax preference, %S" value))
  1143.   (if symbol
  1144.       (setq-default viper-syntax-preference value)
  1145.     (setq viper-syntax-preference value))
  1146.   (viper-update-syntax-classes))
  1147.  
  1148. (defcustom viper-syntax-preference 'reformed-vi
  1149.   "*Syntax type characterizing Viper's alphanumeric symbols.
  1150. Affects movement and change commands that deal with Vi-style words.
  1151. Works best when set in the hooks to various major modes.
  1152.  
  1153. `strict-vi' means Viper words are (hopefully) exactly as in Vi.
  1154.  
  1155. `reformed-vi' means Viper words are like Emacs words \(as determined using
  1156. Emacs syntax tables, which are different for different major modes\) with two
  1157. exceptions: the symbol `_' is always part of a word and typical Vi non-word
  1158. symbols, such as `,',:,\",),{, etc., are excluded.
  1159. This behaves very close to `strict-vi', but also works well with non-ASCII
  1160. characters from various alphabets.
  1161.  
  1162. `extended' means Viper word constituents are symbols that are marked as being
  1163. parts of words OR symbols in Emacs syntax tables.
  1164. This is most appropriate for major modes intended for editing programs.
  1165.  
  1166. `emacs' means Viper words are the same as Emacs words as specified by Emacs
  1167. syntax tables.
  1168. This option is appropriate if you like Emacs-style words."
  1169.   :type '(radio (const strict-vi) (const reformed-vi) 
  1170.          (const extended) (const emacs))
  1171.   :set 'viper-set-syntax-preference
  1172.   :group 'viper)
  1173. (make-variable-buffer-local 'viper-syntax-preference)
  1174.  
  1175.  
  1176. ;; addl-chars are characters to be temporarily considered as alphanumerical
  1177. (defun viper-looking-at-alpha (&optional addl-chars)
  1178.   (or (stringp addl-chars) (setq addl-chars ""))
  1179.   (if (eq viper-syntax-preference 'reformed-vi)
  1180.       (setq addl-chars (concat addl-chars "_")))
  1181.   (let ((char (char-after (point))))
  1182.     (if char
  1183.     (if (eq viper-syntax-preference 'strict-vi)
  1184.         (looking-at (concat "[" viper-strict-ALPHA-chars addl-chars "]"))
  1185.       (or
  1186.        ;; or one of the additional chars being asked to include
  1187.        (memq char (viper-string-to-list addl-chars))
  1188.        (and
  1189.         ;; not one of the excluded word chars
  1190.         (not (memq char viper-non-word-characters))
  1191.         ;; char of the Viper-word syntax class
  1192.         (memq (char-syntax char)
  1193.           (viper-string-to-list viper-ALPHA-char-class))))))
  1194.     ))
  1195.  
  1196. (defun viper-looking-at-separator ()
  1197.   (let ((char (char-after (point))))
  1198.     (if char
  1199.     (if (eq viper-syntax-preference 'strict-vi)
  1200.         (memq char (viper-string-to-list viper-strict-SEP-chars))
  1201.       (or (eq char ?\n) ; RET is always a separator in Vi
  1202.           (memq (char-syntax char)
  1203.             (viper-string-to-list viper-SEP-char-class)))))
  1204.     ))
  1205.  
  1206. (defsubst viper-looking-at-alphasep (&optional addl-chars)
  1207.   (or (viper-looking-at-separator) (viper-looking-at-alpha addl-chars)))
  1208.  
  1209. (defun viper-skip-alpha-forward (&optional addl-chars)
  1210.   (or (stringp addl-chars) (setq addl-chars ""))
  1211.   (viper-skip-syntax
  1212.    'forward 
  1213.    (cond ((eq viper-syntax-preference 'strict-vi)
  1214.       "")
  1215.      (t viper-ALPHA-char-class))
  1216.    (cond ((eq viper-syntax-preference 'strict-vi)
  1217.       (concat viper-strict-ALPHA-chars addl-chars))
  1218.      (t addl-chars))))
  1219.  
  1220. (defun viper-skip-alpha-backward (&optional addl-chars)
  1221.   (or (stringp addl-chars) (setq addl-chars ""))
  1222.   (viper-skip-syntax
  1223.    'backward 
  1224.    (cond ((eq viper-syntax-preference 'strict-vi)
  1225.       "")
  1226.      (t viper-ALPHA-char-class))
  1227.    (cond ((eq viper-syntax-preference 'strict-vi)
  1228.       (concat viper-strict-ALPHA-chars addl-chars))
  1229.      (t addl-chars))))
  1230.  
  1231. ;; weird syntax tables may confuse strict-vi style
  1232. (defsubst viper-skip-all-separators-forward (&optional within-line)
  1233.   (if (eq viper-syntax-preference 'strict-vi)
  1234.       (if within-line 
  1235.       (skip-chars-forward viper-strict-SEP-chars-sans-newline)
  1236.     (skip-chars-forward viper-strict-SEP-chars))
  1237.     (viper-skip-syntax 'forward
  1238.                viper-SEP-char-class
  1239.                (or within-line "\n")
  1240.                (if within-line (viper-line-pos 'end)))))
  1241. (defsubst viper-skip-all-separators-backward (&optional within-line)
  1242.   (if (eq viper-syntax-preference 'strict-vi)
  1243.       (if within-line 
  1244.       (skip-chars-backward viper-strict-SEP-chars-sans-newline)
  1245.     (skip-chars-backward viper-strict-SEP-chars))
  1246.     (viper-skip-syntax 'backward
  1247.                viper-SEP-char-class
  1248.                (or within-line "\n")
  1249.                (if within-line (viper-line-pos 'start)))))
  1250. (defun viper-skip-nonseparators (direction)
  1251.   (viper-skip-syntax
  1252.    direction
  1253.    (concat "^" viper-SEP-char-class)
  1254.    nil
  1255.    (viper-line-pos (if (eq direction 'forward) 'end 'start))))
  1256.  
  1257.  
  1258. ;; skip over non-word constituents and non-separators
  1259. (defun viper-skip-nonalphasep-forward ()
  1260.   (if (eq viper-syntax-preference 'strict-vi)
  1261.       (skip-chars-forward
  1262.        (concat "^" viper-strict-SEP-chars viper-strict-ALPHA-chars))
  1263.     (viper-skip-syntax
  1264.      'forward
  1265.      (concat "^" viper-ALPHA-char-class viper-SEP-char-class)
  1266.      ;; Emacs may consider some of these as words, but we don't want them
  1267.      viper-non-word-characters 
  1268.      (viper-line-pos 'end))))
  1269. (defun viper-skip-nonalphasep-backward ()
  1270.   (if (eq viper-syntax-preference 'strict-vi)
  1271.       (skip-chars-backward
  1272.        (concat "^" viper-strict-SEP-chars viper-strict-ALPHA-chars))
  1273.     (viper-skip-syntax
  1274.      'backward
  1275.      (concat "^" viper-ALPHA-char-class viper-SEP-char-class)
  1276.      ;; Emacs may consider some of these as words, but we don't want them
  1277.      viper-non-word-characters
  1278.      (viper-line-pos 'start))))
  1279.  
  1280. ;; Skip SYNTAX like skip-syntax-* and ADDL-CHARS like skip-chars-*
  1281. ;; Return the number of chars traveled.
  1282. ;; Both SYNTAX or ADDL-CHARS can be strings or lists of characters.
  1283. ;; When SYNTAX is "w", then viper-non-word-characters are not considered to be
  1284. ;; words, even if Emacs syntax table says they are.
  1285. (defun viper-skip-syntax (direction syntax addl-chars &optional limit)
  1286.   (let ((total 0)
  1287.     (local 1)
  1288.     (skip-chars-func
  1289.      (if (eq direction 'forward)
  1290.          'skip-chars-forward 'skip-chars-backward))
  1291.     (skip-syntax-func
  1292.      (if (eq direction 'forward)
  1293.          'viper-forward-char-carefully 'viper-backward-char-carefully))
  1294.     char-looked-at syntax-of-char-looked-at negated-syntax)
  1295.     (setq addl-chars
  1296.       (cond ((listp addl-chars) (viper-charlist-to-string addl-chars))
  1297.         ((stringp addl-chars) addl-chars)
  1298.         (t "")))
  1299.     (setq syntax
  1300.       (cond ((listp syntax) syntax)
  1301.         ((stringp syntax) (viper-string-to-list syntax))
  1302.         (t nil)))
  1303.     (if (memq ?^ syntax) (setq negated-syntax t))
  1304.  
  1305.     (while (and (not (= local 0)) (not (eobp)))
  1306.       (setq char-looked-at (viper-char-at-pos direction)
  1307.         ;; if outside the range, set to nil
  1308.         syntax-of-char-looked-at (if char-looked-at
  1309.                      (char-syntax char-looked-at)))
  1310.       (setq local
  1311.         (+ (if (and
  1312.             (cond ((and limit (eq direction 'forward))
  1313.                (< (point) limit))
  1314.               (limit ; backward & limit
  1315.                (> (point) limit))
  1316.               (t t)) ; no limit
  1317.             ;; char under/before cursor has appropriate syntax
  1318.             (if negated-syntax
  1319.             (not (memq syntax-of-char-looked-at syntax))
  1320.               (memq syntax-of-char-looked-at syntax))
  1321.             ;; if char-syntax class is "word", make sure it is not one
  1322.             ;; of the excluded characters
  1323.             (if (and (eq syntax-of-char-looked-at ?w)
  1324.                  (not negated-syntax))
  1325.             (not (memq char-looked-at viper-non-word-characters))
  1326.               t))
  1327.            (funcall skip-syntax-func 1)
  1328.          0)
  1329.            (funcall skip-chars-func addl-chars limit)))
  1330.       (setq total (+ total local)))
  1331.     total
  1332.     ))
  1333.   
  1334.  
  1335.   
  1336. (provide 'viper-util)
  1337.   
  1338.  
  1339. ;;; Local Variables:
  1340. ;;; eval: (put 'viper-deflocalvar 'lisp-indent-hook 'defun)
  1341. ;;; End:
  1342.  
  1343. ;;;  viper-util.el ends here
  1344.